package com.fire.security.aspect;

import com.fire.security.annotation.AutoFill;
import com.fire.security.constant.AutoFillConstant;
import com.fire.security.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.fire.security.mapper.*.*(..)) && @annotation(com.fire.security.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void atuoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("公共字段填充中，当前方法为{}",joinPoint.getSignature().toString());
        MethodSignature localMethod = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = localMethod.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object objects = args[0];
        LocalDateTime now = LocalDateTime.now();
        Date nowDate = toDate(now);
        System.out.println(nowDate);
        if (operationType == OperationType.INSERT){
            Method setCreateTime = objects.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,Date.class);
            Method setUpdateTime = objects.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,Date.class);
            setCreateTime.invoke(objects,nowDate);
            setUpdateTime.invoke(objects,nowDate);
        }else  if (operationType == OperationType.UPDATE){
            Method setUpdateTime = objects.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,Date.class);
            setUpdateTime.invoke(objects,nowDate);

        }
    }
    public static Date toDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

}
